package com.dd.ms.auth.controller;

import com.dd.ms.auth.pojo.resp.AuthResponse;
import com.dd.ms.auth.pojo.resp.RefreshTokenResponse;
import com.dd.ms.auth.req.LoginReq;
import com.dd.ms.auth.req.RegisterReq;
import com.dd.ms.auth.service.AuthService;
import com.dd.ms.common.response.ApiResponse;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Encoders;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/7/8 16:31
 * @Description 认证控制器 - 处理用户登录和令牌颁发
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Api(tags = "认证控制器（处理用户登录和令牌颁发）")
public class AuthController {

    private final AuthService authService;

    @PostMapping("/gene-jwt-secret-key")
    @ApiOperation("生成JWT签名密钥")
    public ApiResponse<String> geneSecretKey() {
        // 生成符合HS512安全要求的密钥
        SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS512); // 512-bit key
        // such as: S+fiwuWQORY7ScLeyf2iX+F7sl9Xy9WfkchQhUOdQLd+a0FAEbvUt0/zoPHhNOfZs2x4uZ4ed+OdY0ujuJ+c5g==
        return ApiResponse.success(Encoders.BASE64.encode(key.getEncoded()));
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ApiResponse<AuthResponse> register(@Valid @RequestBody @ApiParam("注册请求") RegisterReq req) {
        log.info("req = " + req);
        return ApiResponse.success(authService.register(req));
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ApiResponse<AuthResponse> login(@Valid @RequestBody @ApiParam("登录请求") LoginReq req, HttpServletRequest request) {
        log.info("req = " + req);
        return ApiResponse.success(authService.login(req, request));
    }

    @ApiOperation("刷新token")
    @PostMapping("/token-refresh")
    public ApiResponse<RefreshTokenResponse> refreshToken(
            @RequestHeader("Authorization-R") String refreshToken, HttpServletRequest request) {
        // 剥离"Bearer "前缀
        String token = refreshToken.replace("Bearer ", "");
        return ApiResponse.success(authService.refreshToken(token, request));
    }

    @ApiOperation("用户登出")
    @PostMapping("/logout")
    public ApiResponse<Void> logout(@RequestHeader("Authorization") String accessToken) {
        log.info("accessToken = " + accessToken);
        String token = accessToken.replace("Bearer ", "");
        authService.logout(token);
        return ApiResponse.success();
    }
}
